package com.haiyou.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author chenzeke
 * redis工具类
 **/
@Component
@Slf4j
public class RedisUtil {
    public static String SESSION = "session_";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate2;
    @Autowired
    private ValueOperations<String, String> valueOperations;

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, String value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public String get(String key) {
        return valueOperations.get(key);
    }

    /**
     * 原子自增
     *
     * @param key
     * @param delta
     * @return
     */
    public Long increment(String key, long delta) {
        return valueOperations.increment(key, delta);
    }


    public List<Integer> getSessionUserId(Integer userId) {
        String sessionKey = SESSION + userId;
        Set<String> userIds = redisTemplate2.opsForZSet().range(sessionKey, 0, -1);
        List<Integer> list = new ArrayList<>();
        if (userIds != null && userIds.size() > 0) {
            userIds.forEach(str -> {
                try {
                    list.add(Integer.valueOf(str.replace("userId_", "")));
                } catch (NumberFormatException e) {
                    log.error("错误会话ID==>" + str);
                    return;
                }
            });
        }
        return list;
    }
}


